import React, { Component } from "react";
import login from "../hooks/loginInfo";
import { Redirect } from "react-router-dom";
import "../assets/css/Cart.css";
import PageHeader from "../components/PageHeader";
import CartItem from "../components/CartItem";
import { successToast, errorToast } from "../components/Toast";
import Loading from "../components/Loading";

class Cart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLogin: "",
      shopBagList: null,
      admin: false,
      totalNum: 0,
      totalPrice: 0,
      totalCheck: 0,
      checked: false,
      timer: null,
      token: null,
    };
    this.toggleAdmin = this.toggleAdmin.bind(this);
    this.toggleCheckBox = this.toggleCheckBox.bind(this);
    this.submitOrder = this.submitOrder.bind(this);
    this.checkItem = this.checkItem.bind(this);
    this.changeNum = this.changeNum.bind(this);
    this.delSelected = this.delSelected.bind(this);
  }

  delSelected() {
    var list = this.state.shopBagList;
    var sids = [];
    list = list.filter((item) => {
      if (item["checked"]) {
        sids.push(item.sid);
      }
      return !item["checked"];
    });
    if (sids.length === 0) {
      errorToast("请选择商品");
    } else {
      this.$axios
        .post("/removeShopcart", {
          tokenString: this.state.token,
          sids: JSON.stringify(sids),
        })
        .then((res) => {
          successToast(res.data.msg);
        });
      this.setState({
        shopBagList: list,
        totalNum: 0,
        totalPrice: 0,
      });
    }
  }

  checkItem(sid) {
    var list = this.state.shopBagList;
    var index = this.state.shopBagList.findIndex((item) => {
      return item.sid === sid;
    });
    list[index]["checked"] = !list[index]["checked"];
    this.setState({
      shopBagList: list,
    });
    var totalPrice = 0;
    var totalNum = 0;
    var allNum = 0;
    list.forEach((item) => {
      if (item["checked"]) {
        allNum++;
        totalPrice += item.price * item.count;
        totalNum += item.count;
      }
    });
    if (allNum === this.state.shopBagList.length) {
      this.setState({
        checked: true,
      });
    } else {
      this.setState({
        checked: false,
      });
    }
    this.setState({
      totalPrice,
      totalNum,
    });
  }

  submitOrder() {
    var list = this.state.shopBagList;
    var sids = [];
    list.filter((item) => {
      if (item["checked"]) {
        sids.push(item.sid);
      }
      return true;
    });
    if (sids.length === 0) {
      errorToast("请选择商品");
    } else {
      this.props.history.push({
        pathname: "/orderDetail",
        query: {
          sid: sids,
        },
      });
    }
  }

  changeNum(sid, symbol) {
    var index = this.state.shopBagList.findIndex((item) => {
      return item.sid === sid;
    });
    var list = this.state.shopBagList;
    if (symbol === "+") {
      list[index]["count"] = list[index]["count"] + 1;
    } else {
      list[index]["count"] = list[index]["count"] - 1;
      if (list[index]["count"] <= 0) {
        list[index]["count"] = 1;
      }
    }
    var totalPrice = 0;
    var totalNum = 0;
    list.forEach((item) => {
      if (item["checked"]) {
        totalPrice += item.price * item.count;
        totalNum += item.count;
      }
    });
    clearTimeout(this.state.timer);
    var timer = setTimeout(() => {
      this.$axios
        .post("/modifyShopcartCount", {
          tokenString: this.state.token,
          sid,
          count: list[index]["count"],
        })
        .then((res) => {
          console.log(res);
        });
    }, 300);
    this.setState({
      shopBagList: list,
      timer,
      totalPrice,
      totalNum,
    });
  }

  toggleCheckBox() {
    var list = this.state.shopBagList;
    var totalPrice = 0;
    var totalNum = 0;
    if (!this.state.checked) {
      list.forEach((item, index) => {
        list[index]["checked"] = true;
        totalPrice += item.price * item.count;
        totalNum += item.count;
      });
    } else {
      list.forEach((item, index) => {
        list[index]["checked"] = false;
      });
      totalPrice = 0;
      totalNum = 0;
    }
    this.setState({
      checked: !this.state.checked,
      shopBagList: list,
      totalNum,
      totalPrice,
    });
  }

  toggleAdmin() {
    this.setState({
      admin: !this.state.admin,
    });
  }

  componentWillMount() {
    var loginInfo = login();
    this.setState({
      isLogin: loginInfo.isLogin,
      token: loginInfo.token,
    });

    if (!loginInfo.isLogin) {
      localStorage.setItem("ToLoginPage", JSON.stringify({ path: "/cart" }));
    } else {
      this.$axios
        .get("/findAllShopcart", {
          params: {
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          var list = res.data.result;
          list.forEach((item, index) => {
            list[index]["checked"] = false;
          });
          this.setState({
            shopBagList: list,
          });
        });
    }
  }

  render() {
    return this.state.isLogin ? (
      <div className="Cart">
        {this.state.shopBagList ? (
          <React.Fragment>
            <PageHeader>
              <span slot="title">购物袋</span>
              <div
                style={{ opacity: this.state.shopBagList.length <= 0 ? 0 : 1 }}
                slot="right"
                className="cart_admin"
                onClick={this.toggleAdmin}
              >
                {this.state.admin ? <span>完成</span> : <span>编辑</span>}
              </div>
            </PageHeader>

            {this.state.shopBagList.length <= 0 ? (
              <div className="cart_none">
                <div className="cart_none_empty">
                  <img
                    src={require("../assets/images/empty.png").default}
                    alt=""
                  />
                  <span>购物袋空空如也，去逛一逛！</span>
                </div>
                <button
                  className="cart_none_btn"
                  onClick={() => this.props.history.push("/")}
                >
                  去逛一逛
                </button>
              </div>
            ) : (
              <div className="cart_content">
                <div className="cart_content_header">
                  <img
                    src={require("../assets/images/shopbag_bg.png").default}
                    alt=""
                  />
                </div>
                <ul className="cart_content_list">
                  {this.state.shopBagList.map((item) => {
                    return (
                      <CartItem
                        item={item}
                        key={item.sid}
                        checkItem={this.checkItem}
                        changeNum={this.changeNum}
                      ></CartItem>
                    );
                  })}
                </ul>
                <div className="cart_footer">
                  <div
                    className="AddressItem_checkBox"
                    onClick={this.toggleCheckBox}
                  >
                    {this.state.checked ? (
                      <i className="checked_active"></i>
                    ) : (
                      <i className="checked_no"></i>
                    )}
                    <span>全选（{this.state.totalNum}）</span>
                  </div>
                  {!this.state.admin ? (
                    <div className="cart_total">
                      <div>
                        <span>合计：</span>
                        <span>￥{this.state.totalPrice + ".00"}</span>
                      </div>
                      <button
                        onClick={this.submitOrder}
                        className={this.state.totalNum ? "" : "active"}
                      >
                        提交订单
                      </button>
                    </div>
                  ) : (
                    <div className="cart_total">
                      <button onClick={this.delSelected}>删除选择</button>
                    </div>
                  )}
                </div>
              </div>
            )}
          </React.Fragment>
        ) : (
          <Loading></Loading>
        )}
      </div>
    ) : (
      <Redirect to="/login"></Redirect>
    );
  }
}

export default Cart;
